package com.springlearn.springsecurity.service;

import com.springlearn.springsecurity.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 实现UserDetailsService接口中的方法 loadUserByUsername
 * 这里是为SpringSecurity配置类服务的
 *
 *
 * 配置登录用户名是什么
 * 配置登录密码是什么
 * 配置权限是什么（权限是要写在GrantedAuthority--授予权限，SimpleGrantedAuthority--简单授权）
 * 意思就是将对应角色写到一个集合里面返回到配置类中
 *然后return org.springframework.security.core.userdetails.User这个类
 *
 * @author llj
 * @create 2022-04-19 21:13
 */
@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUser(username);
        if(user==null){
            throw new RuntimeException("用户名错误");
        }
        String role=user.getRole();

        //角色集合
        List<GrantedAuthority> list=new ArrayList<>();

        //角色必须以`ROLE_`开头，数据库中没有，则在这里加
        list.add(new SimpleGrantedAuthority("ROLE_"+role));
        return new org.springframework.security.core.userdetails.User(user.getUsername(),passwordEncoder.encode(user.getPassword()),list);

    }
}
